<template>
    <div class="content-wrapper a-base-container">
        <div class="big-main-wrapper">
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :span="2" v-if="permissions.includes('productionLine:add')">
                            <a-dropdown class="btns" key="new" style="display:block">
                                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                    <a-icon class="btns-icon" type="file-add" />
                                    <div class="btns-text">新增
                                        <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                    </div>
                                </a>
                                <a-menu slot="overlay">
                                    <a-menu-item key="0">
                                        <a href="javascript:void(0)" @click="addTemplate">新增</a>
                                    </a-menu-item>
                                    <a-menu-item key="0">
                                        <a href="javascript:void(0)" @click="() => {this.tMoal = true}">选择模版</a>
                                    </a-menu-item>
                                </a-menu>
                            </a-dropdown>
                        </a-col>
                        <a-col :span="2" v-if="permissions.includes('productionLine:edit')">
                            <div class="btns" @click="showModal">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="permissions.includes('productionLine:delete')">
                            <div class="btns" @click="deleteTemplate">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <!-- user table列表 -->
            <div style="width:1000px">
                <a-table :columns="columns" :data-source="data" bordered :scroll="{ x: 0, y: 800}" :row-selection="{selectedRowKeys: selectedKeys, onChange: userSelection}" style="height: calc(100vh - 12rem);margin-top:2px;overflow-y:auto;"></a-table>
            </div>
        </div>

        <!-- 模版选择 -->
        <a-modal v-model="tMoal" centered title='选择模版' width="350px">
            <div id="components-form-demo-advanced-search">
                <a-select style="width:180px">
                    <a-select-option v-for="(item,index) in templateData" :key="index" :value="item.id">{{item.name}}</a-select-option>
                </a-select>
            </div>
        </a-modal>

        <nly-content>
            <!-- modal合同编辑 弹窗  -->
            <a-modal v-model="editModal" centered :title="editItem.id ? '编辑合同' : '新增合同'" width="950px">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" @submit="handleSubmit">
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="合同编码">
                                    <a-input v-decorator="['contractName', { rules: [{ required: true, message: '合同编码不能为空' }] }]" placeholder="请输入合同编码" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="合同名称">
                                    <a-input v-decorator="['contractName', { rules: [{ required: true, message: '合同名称不能为空' }] }]" placeholder="请输入合同名称" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="我方签约人">
                                    <a-input v-decorator="['personCharge', { rules: [{ required: true, message: '我方签约人不能为空' }] }]" placeholder="请输入我方签约人" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="客户方签约人">
                                    <a-input v-decorator="['crmCharge', { rules: [{ required: true, message: '客户方签约人不能为空' }] }]" placeholder="请输入客户方签约人" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="合同金额">
                                    <a-input v-decorator="['contractPrice', { rules: [{ required: true, message: '合同金额不能为空' }] }]" placeholder="请输入合同金额" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="签约时间">
                                    <a-input v-decorator="['signingDate', { rules: [{ required: true, message: '签约时间不能为空' }] }]" placeholder="请输入签约时间" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="生效时间">
                                    <a-input v-decorator="['beginDate', { rules: [{ required: true, message: '生效时间不能为空' }] }]" placeholder="请输入生效时间" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="结束时间">
                                    <a-input v-decorator="['endDate', { rules: [{ required: true, message: '结束时间不能为空' }] }]" placeholder="请输入结束时间" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="合同类型">
                                    <a-select>
                                        <a-select-option :value=1>产品销售</a-select-option>
                                        <a-select-option :value=2>服务</a-select-option>
                                        <a-select-option :value=3>业务合作</a-select-option>
                                        <a-select-option :value=4>代理分销</a-select-option>
                                        <a-select-option :value=5>其它</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="执行状态">
                                    <a-select>
                                        <a-select-option :value=1>执行中</a-select-option>
                                        <a-select-option :value=2>结束</a-select-option>
                                        <a-select-option :value=3>意外中止</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="合同条款">
                                    <a-input v-decorator="['contractClause', { rules: [{ required: true, message: '合同条款不能为空' }] }]" placeholder="请输入合同条款" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="付款方式">
                                    <a-select>
                                        <a-select-option :value=1>汇票</a-select-option>
                                        <a-select-option :value=2>现金</a-select-option>
                                        <a-select-option :value=3>银行转帐</a-select-option>
                                        <a-select-option :value=4>其它</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="付款时间">
                                    <a-input v-decorator="['paymentDate', { rules: [{ required: true, message: '付款时间不能为空' }] }]" placeholder="请输入付款时间" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="付款金额">
                                    <a-input v-decorator="['paymentPrice', { rules: [{ required: true, message: '付款金额不能为空' }] }]" placeholder="请输入付款金额" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="备注">
                                    <a-input v-decorator="['remarks', { rules: [{ required: true, message: '付款金额不能为空' }] }]" placeholder="请输入付款金额" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row :gutter="24">
                            <a-col :span="12">
                                <a-form-item label="内容">
                                    <div class="edit-box">
                                        <ueditor :content.sync="editHtml"></ueditor>
                                    </div>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="handleSubmit" v-if="permissions.includes('productionLine:save')">保存</a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="hideModal">关闭</a-button>
                </template>
            </a-modal>
            <a-modal :visible="officeModal" lg hide-footer title="部门选择" @cancel="hideOfficeModal" size="sm">
                <div style="height: 400px;overflow-y:scroll;">
                    <a-input-search style="margin-bottom: 8px" placeholder="部门名称" @change="onChange" />
                    <a-tree :expanded-keys="expandedOfficeKeys" :selected-keys="selectedOfficeKeys" :tree-data="officeTreeData" @expand="onOfficeExpand" @select="onOfficeSelect" :show-line="true" />
                </div>
                <template slot="footer">
                    <a-row>
                        <a-col :span="24" :style="{ textAlign: 'right' }">
                            <a-button type="primary" html-type="submit" @click="saveOffice">保存</a-button>
                            <a-button :style="{ marginLeft: '8px' }" @click="hideOfficeModal">关闭</a-button>
                        </a-col>
                    </a-row>
                </template>
            </a-modal>
        </nly-content>
    </div>
</template>

<script>

import ueditor from '@/components/Ueditor/index';
import { mapState } from "vuex";
import { FormInput, EditableCell } from "@/components/Form";
import { getTemplateList, saveContractTemplate, deleteContractTemplate, pageList, save, deleteContract } from "@/api/crm/contract";
import { PageList as PageOfficeList } from "@/api/office";
import importAndExport from "@/components/ImportAndExport/emploee"

let keyMap = new Map();

/**
 * 部门数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
    list.forEach(item => {
        // 判断是否为父级菜单
        if (item.parentId === parentId) {
            const child = {
                ...item,
                key: item.id,
                title: item.officeName,
                children: []
            };
            // 迭代 list， 找到当前菜单相符合的所有子菜单
            listToTree(list, child.children, item.id);
            // 删掉不存在 children 值的属性
            if (child.children.length <= 0) {
                delete child.children;
            }
            // 加入到树中
            tree.push(child);
        }
    });
};

//获取父级key
const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};

export default {
    props: {
        dataList: {
            type: Array,
            default: () => []
        }
    },
    components: {
        FormInput,
        EditableCell,
        importAndExport,
        ueditor
    },
    data () {
        const columns = [
            //合同信息table
            {
                align: "left",
                title: "合同编号",
                dataIndex: "contractCode",
                width: "40"
            },
            {
                align: "left",
                title: "合同名称",
                dataIndex: "contractName",
                width: "40"
            },
            {
                align: "left",
                title: "我方签约人",
                dataIndex: "personCharge",
                width: "40"
            },
            {
                align: "left",
                title: "客户方签约人",
                dataIndex: "crmCharge",
                width: "40"
            },
            {
                align: "left",
                title: "合同金额",
                dataIndex: "contractPrice",
                width: "40"
            },
            {
                align: "left",
                title: "签约时间",
                dataIndex: "signingDate",
                width: "40"
            },
            {
                align: "left",
                title: "生效时间",
                dataIndex: "beginDate",
                width: "40"
            },
            {
                align: "left",
                title: "截止时间",
                dataIndex: "endDate",
                width: "40"
            },
            {
                align: "left",
                title: "合同类型",
                dataIndex: "contractType",
                width: "40"
            },
            {
                align: "left",
                title: "合同条款",
                dataIndex: "contractClause",
                width: "40"
            },
            {
                align: "left",
                title: "付款方式",
                dataIndex: "paymentMethod",
                width: "40"
            },
            {
                align: "left",
                title: "付款金额",
                dataIndex: "paymentPrice",
                width: "40"
            },
            {
                align: "left",
                title: "描述",
                dataIndex: "remarks",
                width: "40"
            },
        ];

        const treeData = [];

        return {
            editHtml: '',
            isShow: "display:block",
            editModal: false,
            isDisabled: false,
            autoExpandParent: true,
            expandedOfficeKeys: [],
            checkedOfficeKeys: [], //office tree默认选中的key
            selectedOfficeKeys: [],
            officeName: "", //部门id
            officeId: [], //部门名称
            treeData,
            officeTreeData: [],
            form: this.$form.createForm(this, { name: "advanced_search" }),
            formLayout: "horizontal",
            expand: false,
            postData: {},
            pagination: {
                defaultPageSize: 20,
                size: "small",
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            data: [],
            columns,
            show: false, //是否显示弹窗
            editItem: {}, //新增/编辑对象
            TreeSortEditList: new Map(), //菜单排序修改集合
            selectedRowKeys: [], //角色table选中key
            selectedKeys: [], //合同table选中key
            selectedData: [],
            isRoleTableShow: true, //是否显示
            templateData: [], //模版数据
            tMoal: false,
            officeModal: false,
        };
    },
    mounted () {
        this.pageList();
        this.getTemplateList();
        //this.getOfficeTreeData();
    },
    computed: {
        componentSelectList: function () {
            const dataList = new Array();
            constantRouterComponentsKeys().forEach(item => {
                dataList.push({ key: item, title: item });
            });
            return dataList;
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    methods: {
        userSelection (keys, info) {
            this.selectedKeys = [];
            this.selectedKeys = keys;
            console.log("rowKeys", this.selectedKeys);

            this.selectedData = info;
        },
        hideModal () {
            this.editModal = false;
            this.roleModal = false;
        },
        hideOfficeModal () {
            // this.$refs["officeModal"].hide();
            this.officeModal = false;
        },
        //获取模版列表
        getTemplateList () {
            getTemplateList().then(res => {
                if (res.code == 200) {
                    this.templateData = res.data;
                }
            });
        },
        //获取合同列表
        pageList () {
            const { postData } = this;
            pageList(postData)
                .then(response => {
                    console.log("获取合同列表", response);
                    if (response.code === 200) {
                        this.data = response.data;
                    }
                })
                .catch(error => { });
        },
        //新增合同
        addTemplate () {
            this.editItem = {};
            this.editModal = true;
            this.officeId = null;
            this.officeName = "";
            this.form = this.$form.createForm();
        },
        //编辑合同
        showModal () {
            if (this.selectedKeys.length != 1) {
                this.$message.warning("请选择一条数据");
                return;
            }
            let editItem = this.selectedData[0];
            this.expandedKeys = [];
            this.editItem = { ...editItem };
            this.editHtml = editItem.content;
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        name: this.$form.createFormField({
                            value: editItem.name
                        }),
                    };
                }
            });
            this.editModal = true;
        },
        reset () {
            this.postData = {};
        },
        onCellChange (item, dataIndex, editValue) {
            if (item[dataIndex] != editValue) {
                const edit = { id: item.id, [dataIndex]: editValue };
                this.TreeSortEditList.set(item.id, edit);
            } else {
                this.TreeSortEditList.delete(item.id);
            }
            console.log([...this.TreeSortEditList.values()]);
        },
        handleSubmit (e) {
            //合同保存提交
            e.preventDefault();
            this.form.validateFields((err, values) => {
                this.editItem.content = this.editHtml;
                this.editItem.name = values.name;
                console.log("开始保存:", this.editItem);

                if (!err) {
                    saveContractTemplate(this.editItem).then(response => {
                        console.log(response)
                        if (response.code === 200) {
                            this.$message.success("保存成功")
                            this.selectedKeys = [];
                            this.selectedData = [];
                            //刷新 列表
                            this.pageList();
                            this.hideModal();
                        } else {
                            this.$message.error("保存失败");
                        }
                    });
                }
            });
        },
        deleteTemplate () {
            let _this = this;
            if (this.selectedKeys.length != 1) {
                _this.$message.warning("请选择一条数据");
                return;
            }

            this.$confirm({
                title: '确认',
                content: <span>您确定要{<span style='color:red;'>删除</span>}该记录吗？</span>,
                onOk () {
                    deleteContractTemplate({ id: _this.selectedData[0].id }).then(response => {
                        if (response.code == 200) {
                            _this.$message.success("删除成功");
                            //刷新 列表
                            _this.pageList();
                            _this.selectedKeys = [];
                            _this.selectedData = [];
                        }
                    });
                },
                onCancel () { },
            });
        },
        handleReset () {
            this.form.resetFields();
        },
        toggle () {
            this.expand = !this.expand;
        },
        //选择部门
        selectOffice () {
            // this.$refs["officeModal"].show();
            this.officeModal = true;
        },
        getOfficeTreeData () {
            PageOfficeList()
                .then(response => {
                    if (response.code === 200) {
                        console.log("获取部门列表===111", response.data);
                        const { data } = response;
                        const childrenNav = [];
                        let keys = [];
                        for (let i = 0; i < data.length; i++) {
                            const node = data[i];
                            const key = node.id;
                            const title = node.officeName;
                            this.dataList.push({ key, title });
                            keys.push(key);
                            keyMap.set(key, title);
                        }
                        console.log("childrenOffice==");
                        listToTree(response.data, childrenNav, 0);
                        console.log("childrenOffice==");
                        this.officeTreeData = childrenNav;
                        this.expandedOfficeKeys = keys;
                        this.selectedOfficeKeys = this.parentId;
                    }
                })
                .catch(error => { });
        },
        //状态change
        handleChange (value) {
            this.postData.status = value;
            this.pageList();
        },
        //以下为dataTree 事件触发
        onOfficeExpand (expandedOfficeKeys) {
            console.log("onExpand", expandedOfficeKeys);
            this.expandedOfficeKeys = expandedOfficeKeys;
            this.autoExpandParent = false;
        },
        onOfficeCheck (checkedOfficeKeys) {
            console.log("onCheck", checkedOfficeKeys);
            this.checkedOfficeKeys = checkedOfficeKeys;
        },
        onOfficeSelect (selectedOfficeKeys, info) {
            console.log("onSelect", info.node.title);
            this.selectedOfficeKeys = selectedOfficeKeys;
        },
        onSelect (key, info) {
            this.postData.officeId = key[0];
            this.pageList();
        }
    }
};
</script>

<style scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
        margin-bottom: 0px !important;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }
    .edit-box {
        width: 800px;
        height: 450px;
        overflow-y: auto;
        padding: 10px;
    }
</style>
<style lang="less">
    @import '~@/style/setting/inventory.less';
</style>